using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;

namespace SimpleFramework
{
    public abstract class Loader : ILoader
    {
        protected int m_State;
        protected string m_Url;
        protected ulong m_FileSize = 0;
        protected int m_TryCount = 0;
        protected UnityEvent<ILoader, float> m_Progress = new UnityEvent<ILoader, float>();
        protected UnityEvent<ILoader, string> m_Failure = new UnityEvent<ILoader, string>();

        public string Url { get { return m_Url; } set { m_Url = value; } }
        public object UserData { get; set; }
        public ulong FileSize { get { return m_FileSize; } set { m_FileSize = value; } }
        public int TryCount { get { return m_TryCount; } set { m_TryCount = value; } }

        public UnityEvent<ILoader, float> onProgress { get { return m_Progress; } }

        public UnityEvent<ILoader, string> onFailure { get { return m_Failure; } }

        public abstract float Progress
        {
            get;
        }

        public abstract bool IsDone
        {
            get;
        }

        public abstract ulong downloadedBytes
        {
            get;
        }



        public virtual void Reset()
        {
            m_State = 0;
            m_TryCount = 0;
            m_Progress.RemoveAllListeners();
            m_Failure.RemoveAllListeners();
        }

        public virtual bool Update()
        {
            if (m_State == 0)
            {
                OnStart();
                m_State = 1;
                return false;
            }
            else if (m_State == 1)
            {
                if (OnUpdate())
                {
                    m_State = 2;
                    OnFinish();
                }
                return false;
            }
            else
            {
                return true;
            }
        }

        protected virtual void OnStart()
        {

        }

        protected virtual bool OnUpdate()
        {
            return true;
        }

        protected virtual void OnFinish()
        {

        }

        public virtual void Abort()
        {
            this.onFailure.RemoveAllListeners();
            this.onProgress.RemoveAllListeners();
            this.onFailure.RemoveAllListeners();
            if (m_State == 0)
            {
                m_State = 2;
            }
        }
    }
}